package com.spzx.common.rabbit.config;

import com.alibaba.fastjson2.JSON;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 服务器启动时，执行rabbitTemplate初始化，设置确认函数和回退函数
 * ApplicationEvent      一些子事件的父类。
 * ApplicationReadyEvent 具体子事件。表示应用程序启动好，IOC容器初始化好，存在相关bean对象了。再进行相关的初始化。
 * 也可以使用相关的注解替代： @EventListener
 */
@Slf4j
@Component
public class RabbitInitConfigApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        this.setUpInitRabbitTemplete();
    }


    private void setUpInitRabbitTemplete() {
        /**
         * 只确认消息是否正确到达 Exchange 中,成功与否都会回调
         *
         * @param correlation 相关数据  非消息本身业务数据
         * @param ack             应答结果
         * @param reason           如果发送消息到交换器失败，错误原因
         */
        this.rabbitTemplate.setConfirmCallback((correlationData, ack, reason) -> {
            if (ack) {
                //消息到交换器成功
                log.info("消息发送到Exchange成功：{}", correlationData);
            } else {
                //消息到交换器失败
                log.error("消息发送到Exchange失败：{}", reason);
                /*GuiguCorrelationData guiguCorrelationData = (GuiguCorrelationData)correlationData;

                if(guiguCorrelationData.isDelay()){ // 延迟消息就不重发消息
                    log.info("延迟插件回退不进行消息重发了");
                    return;
                }*/

                //交换机没收到消息，需要重发：
                this.retrySendMsg(correlationData);
            }
        });

        /**
         * 消息没有正确到达队列时触发回调，如果正确到达队列不执行
         *
         *
         *  对于延迟插件使用：
         *      存在问题。延迟转发消息到队列，也会执行回退函数。不需要执行重试。
         */
        this.rabbitTemplate.setReturnsCallback(returned -> {  //ReturnedMessage
            log.error("Returned: " + returned.getMessage() + "\nreplyCode: " + returned.getReplyCode()
                    + "\nreplyText: " + returned.getReplyText() + "\nexchange/rk: "
                    + returned.getExchange() + "/" + returned.getRoutingKey());

            //队列没有收到消息，需要重发：
            Message message = returned.getMessage();
            MessageProperties messageProperties = message.getMessageProperties();
            String correlationId = messageProperties.getHeader("spring_returned_message_correlation");
            String correlationStr = (String)redisTemplate.opsForValue().get(correlationId);
            GuiguCorrelationData guiguCorrelationData = JSON.parseObject(correlationStr, GuiguCorrelationData.class);

            if(guiguCorrelationData.isDelay()){ // 延迟消息就不重发消息
                log.info("延迟插件回退不进行消息重发了");
                return;
            }

            this.retrySendMsg(guiguCorrelationData);
        });
    }

    //封装消息重发方法：
    private void retrySendMsg(CorrelationData correlationData) {
        GuiguCorrelationData guiguCorrelationData = (GuiguCorrelationData)correlationData;

        int retryCount = guiguCorrelationData.getRetryCount();
        if(retryCount>=3){
            //超过最大重试次数
            log.error("生产者超过最大重试次数，将失败的消息存入数据库用人工处理；给管理员发送邮件；给管理员发送短信；");
            return;
        }
        retryCount++;
        guiguCorrelationData.setRetryCount(retryCount);

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {}

        //必须要先更新缓存，再发消息。否则，重试次数可能会出现问题。
        redisTemplate.opsForValue().set(guiguCorrelationData.getId(),JSON.toJSONString(guiguCorrelationData),10, TimeUnit.MINUTES);

        if(guiguCorrelationData.isDelay()){

            MessagePostProcessor messagePostProcessor = (message)->{
                message.getMessageProperties().setDelay(guiguCorrelationData.getDelayTime()*1000); //延迟时间10秒。单位毫秒数
                return message;
            };

            //延迟消息重发。
            rabbitTemplate.convertAndSend(guiguCorrelationData.getExchange(),
                    guiguCorrelationData.getRoutingKey(),
                    guiguCorrelationData.getMessage(),
                    messagePostProcessor,
                    guiguCorrelationData);

        }else{
            //普通消息重发。
            rabbitTemplate.convertAndSend(guiguCorrelationData.getExchange(),
                    guiguCorrelationData.getRoutingKey(),
                    guiguCorrelationData.getMessage(),
                    guiguCorrelationData);
        }

    }


}
